package com.yidu.sanrenxing.homedata.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yidu.sanrenxing.crudall.dao.AdressMsgMapper;
import com.yidu.sanrenxing.crudall.domain.*;
import com.yidu.sanrenxing.crudall.service.AdressMsgService;
import com.yidu.sanrenxing.crudall.service.OrderComMsgService;
import com.yidu.sanrenxing.crudall.service.OrdersService;
import com.yidu.sanrenxing.crudall.service.UserAdressService;
import com.yidu.sanrenxing.crudall.service.impl.ConfigServiceImpl;
import com.yidu.sanrenxing.crudall.service.impl.KeepSetServiceServiceImpl;
import com.yidu.sanrenxing.crudall.service.impl.KeepsetSerRelServiceImpl;
import com.yidu.sanrenxing.crudall.service.impl.ShoppingServiceImpl;
import com.yidu.sanrenxing.homedata.Encapsulation.*;
import com.yidu.sanrenxing.homedata.domain.*;
import com.yidu.sanrenxing.homedata.service.impl.*;
import com.yidu.sanrenxing.utils.AlipayConfig;
import com.yidu.sanrenxing.utils.ImgFormat;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.*;

import static com.alipay.api.AlipayConstants.CHARSET;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class ComTypeController {
    //商品类型接口
    @Autowired
    ComTypeServiveImpl comTypeServiveImpl;

    //商品系列接口
    @Autowired
    ComSeriesServiceImpl comSeriesServiceImpl;

    //商品接口
    @Autowired
    CommotidyServiceImpl commotidyServiceImpl;

    //图片接口
    @Autowired
    ImageServiceImpl imageServiceImpl;

    //颜色接口
    @Autowired
    ColorServiceImpl colorServiceImpl;

    //配置接口
    @Autowired
    ConfigServiceImpl configServiceImpl;

    //中间表接口
    @Autowired
    KeepsetSerRelServiceImpl keepsetSerRelServiceImpl;

    //服务接口
    @Autowired
    KeepSetServiceServiceImpl keepSetServiceServiceImpl;

    //购物车表接口
    @Autowired
    ShoppingServiceImpl shoppingServiceImpl;

    //用户地址表
    @Autowired
    UserAdressService userAdressService;

    //地址信息表
    @Autowired
    AdressMsgService adressMsgService;

    //订单信息表
    @Autowired
    OrdersService ordersService;

    //订单商品信息编号
    @Autowired
    OrderComMsgService orderComMsgService;

    /**
     * 首页数据api
     * @return
     */
    @GetMapping("/homedata")
    public List<Object> homedatas(){
        //
        List<Object> comType1=new ArrayList<>();
        //获取所以商品类型
        List list=comTypeServiveImpl.selectAllComType();
        //封装数据对象
        ComTypeEn comTypeEn=null;
        //遍历商品类型（向每个商品类型中保存相应数据）
        for (Object o : list) {
            //保存商品类型下相应数据
            List list4=new ArrayList();
            ComType comType=(ComType) o;
            //根据商品类型编号获取相应的商品系列对象集合
            List list1=comSeriesServiceImpl.selectBycomserid(comType.getComtypeid());
            //遍历商品系列集合（向每个商品系列下保存数据）
            for (Object o1 : list1) {
                ComSeries comSeries= (ComSeries) o1;
                //根据商品系列编号获取最小商品编号
                int commid=commotidyServiceImpl.selectByComserid(((ComSeries) o1).getComserid());
                //根据最小商品编号获取商品对象
                Commotidy commotidy=commotidyServiceImpl.selectByComId(commid);
                //获取大图标
                String imgss=Arrays.asList(commotidy.getComimgidgroup().split(";")).get(0);
                //获取大图片第一张
                int imgid= Integer.parseInt(Arrays.asList(imgss.split(",")).get(0));
                //获取图片对象
                Image image=imageServiceImpl.selectByPrimaryKey(imgid);
                //对象封装数据{图片url，商品编号，系列名称，系列状态}
                ComSeriesEn comSeriesEn=new ComSeriesEn(image.getImg(),commid,comSeries.getComsername(),comSeries.getSerstatus());
                //保存封装对象
                list4.add(comSeriesEn);
            }
            //封装数据对象{商品类型名，数据集合}
            comTypeEn=new ComTypeEn(((ComType) o).getComtypename(),list4);
            //最终数据封装
            comType1.add(comTypeEn);
        }
        return comType1;
    }

    /**
     * 首页数据api
     */
    @GetMapping("/one")
    public List comSeriesData(){
        //获取所有商品类型
        List list=comTypeServiveImpl.selectAllComType();
        //封装数据的对象
        ComTypeEn comTypeEn=null;
        List lists=new ArrayList();
        for (Object o : list) {
            ComType comType=(ComType)o;
            //获取商品系列（根据商品类型编号）
            List<ComSeries> comSeriesList = comSeriesServiceImpl.selectBycomserid(((ComType) o).getComtypeid());
            List list1=new ArrayList();
            for (ComSeries comSeries : comSeriesList) {
                //取一个商品id。
                Integer commid=commotidyServiceImpl.selectByComserid(comSeries.getComserid());
                //获取商品对象
                Commotidy commotidy=commotidyServiceImpl.selectByComId(commid);
                //获取图片组中第一个
                int imgid= Integer.parseInt(Arrays.asList(commotidy.getComimgidgroup().split(",")).get(0));
                //获取图片
                Image img= imageServiceImpl.selectByPrimaryKey(imgid);
                //获取颜色
                String color= String.valueOf(colorServiceImpl.selectByPrimaryKey(commotidy.getColorid()).getColorname());
                //封装数据对象1{图片url，商品系列名，颜色，商品价格，商品id，商品状态}
                ComSeriesDataEn comSeriesDataEn=new ComSeriesDataEn(img.getImg(),comSeries.getComsername(),color,commotidy.getPrice(),commotidy.getComid(),comSeries.getSerstatus());
                list1.add(comSeriesDataEn);
            }
            //封装数据对象2
            comTypeEn=new ComTypeEn(((ComType) o).getComtypename(),list1);
            lists.add(comTypeEn);
        }
        return lists;
    }

    /**
     * 为详情页面提供数据，通过一个商品编号查询该商品所在系列，将整个系列的数据提供给前端
     * @param comId
     * @return
     */
    @GetMapping("/detailMsg")
    public List<ByComIdData> getMaxSerComDetailMsgByComId(Integer comId){
        ArrayList<ByComIdData> byComIdData = new ArrayList<>();
        List<String> comIds = comSeriesServiceImpl.selectManyComIdBySerIdAndComId(comId);
        for (String com : comIds) {
            byComIdData.add(this.dataByCommId(Integer.parseInt(com)));
        }
        return byComIdData;
    }

    /**
     * 获取所有商品的信息并赋值给详情页面
     * @return
     */
    @GetMapping("/getAllComMsg")
    public List<ByComIdData> getAllComMsg(){
        ArrayList<ByComIdData> byComIdData = new ArrayList<>();
        List<Integer> allComMsg = comSeriesServiceImpl.getAllComMsg();
        for (Integer comMsg : allComMsg) {
            byComIdData.add(this.dataByCommId(comMsg));
        }
        return byComIdData;
    }

    /**
     * 根据商品编号获取相应信息api：系列图片、大图片、小图片等等
     * @param comId
     * @return
     */
    public ByComIdData dataByCommId(int comId){
        //获取指定id的商品对象
        Commotidy commotidy=commotidyServiceImpl.selectByComId(comId);
        //获取图片编号组
        String comImgIdGriup=commotidy.getComimgidgroup();
        //大小图片数组
        List imgList=Arrays.asList(comImgIdGriup.split(";"));
        //获取大小图片
        List imgMin= Arrays.asList(String.valueOf(imgList.get(0)).split(","));
        //获取大图标
        /*List imgMax= Arrays.asList(String.valueOf(imgList.get(1)).split(","));*/
        //根据商品对象中的系列编号获取系列名称
        ComSeries comSeries = comSeriesServiceImpl.selectByPrimaryKey(commotidy.getComserid());
        String comSerName=comSeries.getComsername();
        //商品颜色
        Color color=colorServiceImpl.selectByPrimaryKey(commotidy.getColorid());
        //获取商品配置
        Config config=configServiceImpl.selectByPrimaryKey(commotidy.getComconfigid());
        //商品描述(修改)
        List describesList= Arrays.asList(commotidy.getDescribes().split(","));
        //获取当前系列下所以商品id
        List commIdList=commotidyServiceImpl.selectByComseridAll(commotidy.getComserid());
        //用于存储当前系列下所以商品
        List<Commotidy> commList=new ArrayList<>();
        List configList=new ArrayList();
        for (Object o : commIdList) {
            commList.add(commotidyServiceImpl.selectByComId((Integer) o));
        }
        //List<String> colorNameList1=new ArrayList<>();
        HashSet<String> colorNameList1 = new HashSet<>();
        //List<String> configNames=new ArrayList<>();
        HashSet<String> configNames = new HashSet<>();
        for (Object o : commList) {
            Commotidy commotidy1 = (Commotidy) o;
            //获取商品系列所以颜色
            colorNameList1.add(colorServiceImpl.selectByPrimaryKey(commotidy1.getColorid()).getColorname());
            //获取商品系列所以配置
            configNames.add(configServiceImpl.selectByPrimaryKey(commotidy1.getComconfigid()).getConfigname());
        }
        List keepids=keepsetSerRelServiceImpl.selectByComSerId(commotidy.getComserid());
        List keepSetSerContentList=new ArrayList();
        for (Object keepid : keepids) {
            keepSetSerContentList.add(keepSetServiceServiceImpl.selectByPrimaryKey((Integer) keepid).getKeepsetsercontent());
        }
        String imgs=comSeriesServiceImpl.selectByPrimaryKey(commotidy.getComserid()).getComimgidgroup();
        List imgLists= Arrays.asList(imgs.split(","));
        //封装数据对象{图片组，小图片，大图片，商品系列名称，颜色名称，配置名，“”，商品描述，商品价格，该商品所有颜色，所有配置，所有服务，一个大图片}
        List<String> tranImgMin = ImgFormat.tranListFormat(comSeriesServiceImpl.selectImgGroupByImgIdGroup(imgMin));
        DetailDataFormat detailDataFormat = new DetailDataFormat(tranImgMin,tranImgMin,comSerName,color.getColorname(),config.getConfigname(),"",describesList,commotidy.getPrice(),colorNameList1,configNames,keepSetSerContentList, tranImgMin.get(0));
        ByComIdData byComIdData=new ByComIdData(comId,comSeries.getComserid(),ImgFormat.tranListFormat(comSeriesServiceImpl.selectImgGroupByImgIdGroup(imgLists)),detailDataFormat);
        return byComIdData;
    }


    /**
     * 购物车数据，根据用户编号查询购物车数据
     * @param userId
     * @return
     */
    @GetMapping("/getCarAllData")
    public List<Object> test(Integer userId){
        List<Shopping> shoppingList=shoppingServiceImpl.selectByUserId(userId);
        List<Object> list=new ArrayList();
        for (Shopping shopping : shoppingList) {
            Map<String,Integer> map1=new HashMap<>();
            //商品编号
            map1.put("comId",shopping.getComid());
            //商品服务
            map1.put("serviceId",shopping.getKeepsetserid());
            //商品数量
            map1.put("proNum",shopping.getShoppingnum());
            //购物车编号
            map1.put("shoppingId",shopping.getShoppingid());
            list.add(map1);
        }
        return list;
    }

    /**
     * 把全部的保修服务编号和名称都查出来
     */
    @GetMapping("/selectAllKeep")
    public List<Object> selectAllKeep(){
        List<Object> list=new ArrayList<>();
        List<KeepSetService> keepSetServiceList=keepSetServiceServiceImpl.selectAll();
        for (KeepSetService keepSetService : keepSetServiceList) {
            Map<String,String> map1=new HashMap<>();
            map1.put("serviceId", String.valueOf(keepSetService.getKeepid()));
            map1.put("serviceContent",keepSetService.getKeepsetsercontent());
            list.add(map1);
        }
        return list;
    }

    /**
     * 删除指定用户的购物车中指定商品
     * @param comId
     * @param userId
     * @return
     */
    @GetMapping("/deleteShoppingCarMsgByComIdAndUserId")
    public Boolean deleteShoppingCarMsgByComIdAndUserId(Integer comId,Integer userId){
        return shoppingServiceImpl.deleteShoppingCarMsgByComIdAndUserId(comId,userId) > 0 ? true : false;
    }

    /**
     * 新增购物车信息
     * @param shopping
     * @return
     */
    @GetMapping("/addShoppingCarMsg")
    public Boolean addShoppingCarMsg( Shopping shopping){
        int count = 0;
        //在新增之前判断该用户的商品是否存在，如果已经存在则直接增加数量即可
        Integer shoppingId = shoppingServiceImpl.queryUserIdAndComIdIfExit(shopping.getUserid(),shopping.getComid());
        if (shoppingId != null){
            //增加购物车对应商品数量通过购物车id
            shoppingServiceImpl.updateShoppingCarById(shoppingId,shopping.getShoppingnum());
        }else {
            count = shoppingServiceImpl.insertSelective(shopping);
        }
        return count > 0 ? true : false;
    }

    /**
     * 修改购物车数量
     * @param shopping
     */
    @GetMapping("/updateShoppingCarData")
    public Boolean updateShoppingCarData(Shopping shopping){
        //先通过userId和comId找到对应的购物车编号
        Integer shoppingId = shoppingServiceImpl.queryUserIdAndComIdIfExit(shopping.getUserid(), shopping.getComid());
        Shopping shopping1 = new Shopping();
        shopping1.setShoppingid(shoppingId);
        shopping1.setShoppingnum(shopping.getShoppingnum());
        //调用修改方法
        return shoppingServiceImpl.updateByPrimaryKeySelective(shopping1) > 0 ? true : false;
    }

    /**
     * 通过用户编号查询该用户所有的地址信息
     * @param userId
     * @return
     */
    @GetMapping("/requestShippingAdsMsgByUserId")
    public List<Object> requestShippingAdsMsgByUserId(Integer userId){
        return userAdressService.getShippingAdsMsgById(userId);
    }

    /**
     * 修改对应用户地址信息
     * @param adressMsg
     * @param userAdress
     * @return
     */
    @GetMapping("/updateShippingCarAdsMsg")
    public Boolean updateShippingCarAdsMsg(AdressMsg adressMsg,UserAdress userAdress){
        if (userAdress.getSelectstatus() == 1){//该用户如果要修改默认状态的话，首先要取消该用户对应所有地址的默认状态
            userAdressService.cancelAllSelectDefaultStatusByUserId(userAdress.getUserid());
        }
        //调用方法修改用户地址表选中状态，通过地址信息表id和用户表id确认是哪一行数据
        userAdressService.updateSelectStatusByUserIdAndAdsId(userAdress);
        //调用方法修改地址信息表，通过地址信息编号
        adressMsgService.updateAdsMsgById(adressMsg);
        //判断当前用户的地址状态是否还有默认，如果没有则设置第一个地址为默认地址,这里是防止用户修改的时候将默认状态取消
        if (userAdressService.ifHaveDefaultSelectStatus(userAdress.getUserid())){
            userAdressService.updateFirstLineDataForDefaultSelect(userAdress.getUserid());
        }
        return true;
    }

    /**
     * 添加对应的用户地址信息和地址信息
     * @param adressMsg
     * @param userAdress
     * @return
     */
    @GetMapping("/addShippingAdsMsg")
    public Boolean addShippingAdsMsg(AdressMsg adressMsg,UserAdress userAdress){
        if (userAdress.getSelectstatus() == 1){//该用户如果要修改默认状态的话，首先要取消该用户对应所有地址的默认状态
            userAdressService.cancelAllSelectDefaultStatusByUserId(userAdress.getUserid());
        }
        //添加地址信息表，返回地址信息编号
        adressMsgService.addAdsMsg(adressMsg);
        //调用用户地址信息
        userAdress.setAdressmsgid(adressMsg.getAdressmsgid());
        int count = userAdressService.insertSelective(userAdress);
        return count > 0 ? true : false;
    }

    /**
     * 删除用户地址信息和地址信息
     * @param adressmsgid
     * @param userid
     * @return
     */
    @GetMapping("/deleteShippingAdsMsg")
    public Boolean deleteShippingAdsMsg(Integer adressmsgid,Integer userid){
        //删除用户地址信息表
        userAdressService.deleteUserAdsMsgByAdrIdAndUserId(adressmsgid,userid);
        //删除地址信息表
        adressMsgService.deleteByPrimaryKey(adressmsgid);
        //判断当前用户的地址状态是否还有默认，如果没有则设置第一个地址为默认地址
        if (userAdressService.ifHaveDefaultSelectStatus(userid)){
            userAdressService.updateFirstLineDataForDefaultSelect(userid);
        }
        return true;
    }

    /**
     * 查询订单信息表
     * @param userId
     * @return
     */
    @GetMapping("/getOrderDataByUserId")
    public List<Object> getOrderDataByUserId(Integer userId){
        List<Orders> orderMsg = ordersService.getOrderDataByUserId(userId);
        ArrayList<Object> list = new ArrayList<>();
        for (Orders orders : orderMsg) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId",orders.getOrderid());
            map.put("orderStatus",orders.getOrderstatus());
            map.put("paymentTime",orders.getPaymenttime());
            map.put("orderComMsgId",orders.getOrdercommsgid());
            map.put("postage",orders.getPostage());
            map.put("total",orders.getTotal());
            map.put("getAdress",orders.getGetadress());
            map.put("paymentWay",orders.getPaymentway());
            map.put("userId",orders.getUserid());
            list.add(map);
        }
        return list;
    }

    /**
     * 获取订单商品信息通过订单编号组
     * @param orderIds
     * @return
     */
    @PostMapping("/getOrderComMsgDataByOrderIds")
    public List<Object> getOrderComMsgDataByOrderIds(String orderIds){
        String[] orderIdArr = orderIds.split(",");
        ArrayList<Object> list = new ArrayList<>();
        for (String orderId : orderIdArr) {
            List<OrderComMsg> orderMsgArr = orderComMsgService.getOrderComMsgByOrderId(orderId);
            for (OrderComMsg orderComMsg : orderMsgArr) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("orderComMsgId",orderComMsg.getOrdercommsgid());
                map.put("comId",orderComMsg.getComid());
                map.put("keepSetSerId",orderComMsg.getKeepsetserid());
                map.put("orderId",orderComMsg.getOrderid());
                map.put("ordernum",orderComMsg.getOrdernum());
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 添加订单信息
     * @param orders
     * @return
     */
    @PostMapping("/addOrderMsg")
    public String addOrderMsg(Orders orders,HttpServletRequest request){
        ordersService.addOrderMsg(orders);
        HttpSession session = request.getSession();
        session.setAttribute("orderId",orders.getOrderid());
        return orders.getOrderid();
    }

    /**
     * 添加订单商品信息表
     * @param orderComMsgList
     * @return
     */
    @PostMapping("/addOrderComMsgData")
    public Boolean addOrderComMsgData(OrderComMsg orderComMsgList){
        orderComMsgService.insertSelective(orderComMsgList);
        return true;
    }

    /**
     * 删除购物车信息，通过商品id和用户编号
     * @param comIds
     * @param userId
     * @return
     */
    @PostMapping("/deleteShoppingCarMg")
    public Boolean deleteShoppingCarMg(String comIds,Integer userId){
        String[] comIdArr = comIds.split(",");
        for (String comId : comIdArr) {
            //通过商品编号和用户编号删除购物车信息，因为通过商品编号和购物车编号就能直接找到对应的唯一一个购物车
            shoppingServiceImpl.deleteShoppingCarMsgByComIdAndUserId(Integer.parseInt(comId),userId);
        }
        return true;
    }

    @RequestMapping("/aliapy")
    public void alipay(Integer money,String description,HttpServletResponse httpResponse) throws IOException {

        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AlipayConfig.return_url);
        request.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount = String.valueOf(money);
        //订单名称，必填
        String subject = description;
        //商品描述，可空
        String body = description;
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = null;
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        PrintWriter out = httpResponse.getWriter();
        out.println(form);
    }

    /**
     * 支付成功跳转到方法
     * @param request
     * @return
     */
    @GetMapping("/alipaySuccess")
    public String alipaySuccess(HttpServletRequest request){
        String orderId = (String)request.getSession().getAttribute("orderId");
        //修改该订单的状态为2已完成，通过订单编号修改订单状态
        ordersService.updateOrderStatusByOrderId(orderId);
        return "forward:http://localhost:8080/#/paymentChildSuccess?orderId=" + orderId;
    }

    /**
     * 取消订单或者判断定时已经超时
     * @param orderId
     * @return
     */
    @PostMapping("/updateOrderStatus")
    public Boolean updateOrderStatus(String orderId){
        //判断该订单对应的状态是否已经完成，如果未完成就直接将其取消
        //未完成修改为取消并返回true，如果已完成或者已取消则不修改并返回false
        return ordersService.updateOrderStatusForCanCel(orderId) > 0 ? true : false;
    }
}
